

class MyBlokingQueue{
    public int head = 0;
    public int tail = 0;
    public int size = 0;
    public String[] data = null;
    public MyBlokingQueue(int i){
        data = new String[i];
    }
    public String take () throws InterruptedException {
        String take ="";
        synchronized (this){
            if(size == 0){
                this.wait();
            }
            take = data[head];
            head++;
            if(head >= data.length){
                head = 0;
            }
            size--;
            this.notify();
        }
        return take;
    }
    public void put(String s) throws InterruptedException {
        synchronized (this){
            if(size == data.length){
                this.wait();
            }
            data[tail] =s;
            tail++;
            if(tail >= data.length){
                tail = 0;
            }
            size++;
            this.notify();
        }
    }
}
public class ApplyBlokingQueue {
    public static void main(String[] args) {
        MyBlokingQueue blokingQueue = new MyBlokingQueue(1000);
        Thread t1 = new Thread(()->{
            int i = 1;
            while(true){
                try {
                    Thread.sleep(1000);
                    blokingQueue.put(""+i);
                    System.out.println("生产元素"+i);
                    i++;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        });
        Thread t2 = new Thread(()->{
            while(true){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    Integer i = Integer.parseInt(blokingQueue.take());
                    System.out.println("消费元素"+i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        t2.start();
    }
}
